import sys
import os
from PyQt5.QtWidgets import (QApplication, QWidget, QLabel, QPushButton,
                             QHBoxLayout, QVBoxLayout, QListWidget, QSlider,
                             QFileDialog)
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent
from PyQt5.QtCore import Qt, QUrl, QTimer, QSize
from PyQt5.QtGui import QPixmap, QFont, QIcon, QColor

def resource_path(relative_path):
    """资源路径处理"""
    try:
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

class AnimePlayer(QWidget):
    def __init__(self):
        super().__init__()
        self.player = QMediaPlayer()
        self.playlist = []
        self.current_index = 0
        self.init_ui()
        self.init_player()

    def init_ui(self):
        """初始化蓝色主题界面"""
        self.setWindowIcon(QIcon(resource_path("resources/icon.ico")))
        self.setWindowTitle("月月音乐播放器")
        self.setGeometry(300, 300, 400, 600)
        self.setStyleSheet(self.load_stylesheet())

        # 主布局
        main_layout = QVBoxLayout()

        # 封面区域
        self.cover_label = QLabel(self)
        self.cover_label.setAlignment(Qt.AlignCenter)
        self.cover_label.setPixmap(QPixmap(resource_path("resources/cover.png")))
        main_layout.addWidget(self.cover_label)

        # 播放控制区域
        control_layout = QHBoxLayout()

        self.btn_prev = self.create_icon_button("prev")
        self.btn_play = self.create_icon_button("play")
        self.btn_next = self.create_icon_button("next")
        self.btn_open = self.create_icon_button("open")

        control_layout.addWidget(self.btn_prev)
        control_layout.addWidget(self.btn_play)
        control_layout.addWidget(self.btn_next)
        control_layout.addWidget(self.btn_open)

        # 进度条
        self.slider = QSlider(Qt.Horizontal)
        self.slider.setStyleSheet(self.slider_style())

        # 播放列表
        self.list_widget = QListWidget()
        self.list_widget.setStyleSheet(self.list_style())
        self.list_widget.itemSelectionChanged.connect(self.highlight_current_song)

        main_layout.addWidget(self.slider)
        main_layout.addLayout(control_layout)
        main_layout.addWidget(self.list_widget)
        self.setLayout(main_layout)

    def init_player(self):
        """初始化播放器组件"""
        self.player.setVolume(50)
        self.slider.sliderMoved.connect(self.set_position)
        self.player.durationChanged.connect(self.update_duration)
        self.player.positionChanged.connect(self.update_position)
        self.player.mediaStatusChanged.connect(self.handle_media_status)
        self.list_widget.itemDoubleClicked.connect(self.play_selected)

    def create_icon_button(self, icon_name):
        """创建图标按钮"""
        btn = QPushButton()
        btn.setObjectName(icon_name)
        btn.setIcon(QIcon(resource_path(f"resources/{icon_name}.png")))
        btn.setIconSize(QSize(32, 32))
        btn.setFixedSize(60, 60)
        btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                stop:0 #4169E1, stop:1 #0000FF);
                border-radius: 30px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                stop:0 #0000FF, stop:1 #4169E1);
            }
        """)
        btn.clicked.connect(self.on_button_click)
        return btn

    def handle_media_status(self, status):
        """处理播放结束"""
        if status == QMediaPlayer.EndOfMedia:
            self.play_next()

    def highlight_current_song(self):
        """高亮当前播放歌曲"""
        for i in range(self.list_widget.count()):
            item = self.list_widget.item(i)
            if i == self.current_index:
                item.setBackground(QColor(65, 105, 225))
                item.setForeground(QColor(255, 255, 255))
            else:
                item.setBackground(QColor(135, 206, 235, 30))
                item.setForeground(QColor(0, 0, 0))

    def play_current(self):
        """播放当前选中歌曲"""
        if self.playlist:
            content = QMediaContent(QUrl.fromLocalFile(self.playlist[self.current_index]))
            self.player.setMedia(content)
            self.player.play()
            self.btn_play.setIcon(QIcon(resource_path("resources/icons/pause.png")))
            self.list_widget.setCurrentRow(self.current_index)
            self.highlight_current_song()

    def play_next(self):
        """播放下一首"""
        if self.playlist:
            self.current_index = (self.current_index + 1) % len(self.playlist)
            self.play_current()

    def play_previous(self):
        """播放上一首"""
        if self.playlist:
            self.current_index = (self.current_index - 1) % len(self.playlist)
            self.play_current()

    def slider_style(self):
        """进度条样式"""
        return """
            QSlider::groove:horizontal {
                height: 8px;
                background: #87CEEB;
                border-radius: 4px;
            }
            QSlider::handle:horizontal {
                background: #4169E1;
                width: 16px;
                margin: -4px 0;
                border-radius: 8px;
            }
        """

    def list_style(self):
        """列表样式"""
        return """
            QListWidget {
                background: rgba(135,206,235, 0.3);
                font-size: 14px;
                color: black;
            }
            QListWidget::item {
                padding: 5px;
            }
        """

    def load_stylesheet(self):
        """主窗口样式"""
        return """
            QWidget {
                background: rgba(135,206,235, 0.1);
            }
            QLabel#cover_label {
                border: 2px solid #4169E1;
                border-radius: 15px;
            }
        """


    def on_button_click(self):
        """按钮点击事件处理:ml-citation{ref="5" data="citationList"}"""
        sender = self.sender()
        if sender.objectName() == "play":
            self.toggle_play()
        elif sender.objectName() == "prev":
            self.play_previous()
        elif sender.objectName() == "next":
            self.play_next()
        elif sender.objectName() == "open":
            self.load_music()


    def toggle_play(self):
        """播放/暂停切换:ml-citation{ref="5" data="citationList"}"""
        if self.player.state() == QMediaPlayer.PlayingState:
            self.player.pause()
            self.btn_play.setIcon(QIcon(resource_path("resources/icons/play.png")))
        else:
            self.player.play()
            self.btn_play.setIcon(QIcon(resource_path("resources/icons/pause.png")))


    def load_music(self):
        """加载音乐文件:ml-citation{ref="5" data="citationList"}"""
        folder = QFileDialog.getExistingDirectory(self, "选择音乐文件夹")
        if folder:
            self.playlist = [os.path.join(folder, f) for f in os.listdir(folder)
                             if f.endswith(('.mp3', '.wav', '.flac'))]
            self.list_widget.clear()
            self.list_widget.addItems([os.path.basename(f) for f in self.playlist])
            if self.playlist:
                self.play_music(0)
                self.play_current()


    def play_music(self, index):
        """播放指定索引的音乐:ml-citation{ref="5" data="citationList"}"""
        if 0 <= index < len(self.playlist):
            self.current_index = index
            media = QMediaContent(QUrl.fromLocalFile(self.playlist[index]))
            self.player.setMedia(media)
            self.player.play()
            self.btn_play.setIcon(QIcon(resource_path("resources/icons/pause.png")))


    def set_position(self, position):
        """设置播放进度:ml-citation{ref="5" data="citationList"}"""
        self.player.setPosition(position)


    def update_duration(self, duration):
        """更新进度条长度:ml-citation{ref="5" data="citationList"}"""
        self.slider.setRange(0, duration)


    def update_position(self, position):
        """更新当前播放位置:ml-citation{ref="5" data="citationList"}"""
        self.slider.setValue(position)


    def play_selected(self, item):
        """双击播放列表项:ml-citation{ref="5" data="citationList"}"""
        index = self.list_widget.row(item)
        self.play_music(index)


    def create_icon_button(self, btn_type):
        """创建图标按钮"""
        btn = QPushButton()
        btn.setObjectName(btn_type)
        btn.setFixedSize(64, 64)

        # 设置图标样式
        icon_path = f"resources/icons/{btn_type}.png"
        btn.setIcon(QIcon(resource_path(icon_path)))
        btn.setIconSize(QSize(48, 48))

        # 按钮样式表
        btn.setStyleSheet("""
                           QPushButton {
                               background: transparent;
                               border: none;
                           }
                           QPushButton:hover {
                               background: rgba(255,105,180, 0.2);
                               border-radius: 32px;
                           }
                       """)
        btn.clicked.connect(self.on_button_click)
        return btn

if __name__ == "__main__":
    app = QApplication(sys.argv)
    player = AnimePlayer()
    player.show()
    sys.exit(app.exec_())
